package com.hospital.hospitalserver.service;


import com.hospital.hospitalserver.entity.DoctorDetail;
import com.hospital.hospitalserver.entity.UserInfo;
import com.hospital.hospitalserver.entity.Vo.Doctor;
import com.hospital.hospitalserver.entity.query.DoctorScheduleQuery;
import com.hospital.hospitalserver.mapper.DepartmentMapper;
import com.hospital.hospitalserver.mapper.DoctorMapper;
import com.hospital.hospitalserver.mapper.UserMapper;
import com.hospital.hospitalserver.util.EncryptHelper;
import com.hospital.hospitalserver.util.Pager;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 医生接口方式实现类
 * */
@Service
@RequiredArgsConstructor
public class DoctorService {
    private final DoctorMapper doctorMapper;
    private final UserMapper userMapper;
    private final DepartmentMapper departmentMapper;

    /**
     * 新增医生
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response addDoctor(DoctorDetail doctor){
        // 1. 判断添加的账户是否存在重复
        UserInfo u = userMapper.findUserByUsername(doctor);
        if(u!=null){
            return Response.error("账户名已存在");
        }

        // 2. 设置默认角色（例如医生角色 role_id = 1）
        doctor.setRole_id(1); // 根据实际角色ID设置
        doctor.setIs_active(1); // 默认激活
        String encryptedPassword = EncryptHelper.SHA(doctor.getUserpass());
        doctor.setUserpass(encryptedPassword);

        // 3. 添加用户，此时 doctor 对象的 user_id 会被自动填充
        Integer addCount = userMapper.addUser(doctor);
        if(addCount==0){
            return Response.error("用户添加失败");
        }

        // 4. 此时 doctor.getUser_id() 已经包含新生成的 user_id
        doctor.setDoctor_id(doctor.getUser_id()); // 共享主键

        // 5. 添加医生详细信息
        Integer count = doctorMapper.addDoctor(doctor);
        if(count>0){
            //添加成功则更新对应科室医生总数
            departmentMapper.UpdateAddDoctorCountByDepartmentId(doctor.getDepartment_id());
            return Response.success();
        }else{
            return Response.error("医生信息添加失败");
        }
    }

    /**
     * 编辑医生信息
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response editDoctor(DoctorDetail doctor){
        // 1.取出医生数据信息
        Doctor doctorInfo = doctorMapper.findByDoctorId(doctor.getDoctor_id());


        Integer counts = doctorMapper.editDoctor(doctor);
        if(counts>0){
            //编辑成功之后判断是否更换了科室，如果更换科室要同步更新各个科室的医生人数
            // 2. 比对科室信息是否有修改
            if(!doctor.getDepartment_id().equals(doctorInfo.getDepartment_id())){
                //变更科室
                //减少原科室医生人数
                departmentMapper.UpdateDeleteDoctorCountByDepartmentId(doctorInfo.getDepartment_id());
                //增加新科室医生人数
                departmentMapper.UpdateAddDoctorCountByDepartmentId(doctor.getDepartment_id());
            }
            return Response.success();
        }
        return Response.error();
    }

    /**
     * 分页功能
     * 根据搜索条件查询医生数据总数
     * */
    private Integer getDoctorCountBySearch(Pager pager){
        return doctorMapper.getDoctorCountBySearch(pager);
    }

    /**
     * 计算分页
     * */
    private Integer getDoctorPageTotalBySearch(Pager pager){
        Integer doctorTotalCounts = getDoctorCountBySearch(pager);
        Integer pageTotal = 1;//设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = doctorTotalCounts/pager.getPageSize();
        if(doctorTotalCounts%pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 分页功能
     * 根据搜索条件查询医生分页数据
     * */
    private List<DoctorDetail> getDoctorMapperDataBySearch(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage - 1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return doctorMapper.getDoctorMapperDataBySearch(pager);
    }

    /**
     * 分页功能
     * 装载医生分页数据信息给前端API
     * */
    public Response getDoctorPagerDataBySearch(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getDoctorCountBySearch(pager));
        pagerData.setPageTotal(getDoctorPageTotalBySearch(pager));
        pagerData.setData(getDoctorMapperDataBySearch(pager));
        return Response.success(pagerData);
    }

    /**
     * 获取医生的列表数据
     * 用于查询检索
     * */
    public Response getDoctorList(){
        return Response.success(doctorMapper.getDoctorList());
    }

    /**
     * 医生工作台
     * 获取当前医生的月视图-周视图-日视图的排班数据
     * */
    public Response queryDoctorScheduleInstanceData(DoctorScheduleQuery query){
        return Response.success(doctorMapper.queryDoctorScheduleInstanceData(query));
    }
}
